package com.whale.cloud.util;

import com.whale.cloud.util.MD5Util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by jiaoshiru on 2017/5/17.
 */
public class AESUtil {
    //    private static Base64 base64 = new Base64();
    private static BASE64Encoder base64Encoder = new BASE64Encoder();
    private static BASE64Decoder base64Decoder = new BASE64Decoder();
    private static final String AES_CIPHER = "AES/ECB/PKCS5Padding";

    // 加密
    public static String encrypt(String msg, String sKey) throws Exception {

        SecretKeySpec skeySpec = new SecretKeySpec(MD5Util.getMD5Byte16(sKey), "AES");

        Cipher cipher = Cipher.getInstance(AES_CIPHER);//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(msg.getBytes("utf-8"));

//        return base64.encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return base64Encoder.encode(encrypted);
    }

    // 解密
    public static String decrypt(String msg, String sKey) throws Exception {

        SecretKeySpec skeySpec = new SecretKeySpec(MD5Util.getMD5Byte16(sKey), "AES");

        Cipher cipher = Cipher.getInstance(AES_CIPHER);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

//        byte[] original = cipher.doFinal(base64.decode(msg));//先用base64解密
        byte[] original = cipher.doFinal(base64Decoder.decodeBuffer(msg));//先用base64解密
        return new String(original, "utf-8");
    }

}
